# -*- coding: utf-8 -*-
import urllib3
import os.path
import argparse
import os
import shutil
import urllib
import zipfile

deps = []
def add_github_depend(name, owner, repo_name, version):
    repo_home_url = 'https://github.com/{}/{}'.format(owner, repo_name)
    download_url = '{}/archive/release-{}.zip'.format(repo_home_url, version)
    deps.append({
        'name': name,
        'owner': owner,
        'repo': repo_name,
        'version': version,
        'home_url': repo_home_url,
        'zipball_url': download_url,
    })

add_github_depend('gtest', 'google', 'googletest', '1.8.1')

parser = argparse.ArgumentParser()
parser.add_argument('--deps-dir', default='.deps', help='deps install root dir')
parser.add_argument('--clear', action='store_true')

def makedir_if_not_exists(dir):
    if os.path.exists(dir) and os.path.isdir(dir):
        return
    os.makedirs(dir)

def rmdir(dir):
    if os.path.exists(dir) and os.path.isdir(dir):
        shutil.rmtree(dir)

def remake_dir(dir):
    if os.path.exists(dir) and os.path.isdir(dir):
        shutil.rmtree(dir)
    os.makedirs(dir)

def extract_zipball(archive_filepath, dest_dir, depend):
    archive = zipfile.ZipFile(archive_filepath)
    name_list = archive.namelist()
    if len(name_list) <= 0:
        raise Exception('{} empty'.format(archive_filepath))

    root_name = name_list[0]
    for name in name_list:
        if not name.startswith(root_name):
            root_name = None
            break
    
    extract_dest = os.path.join(dest_dir, depend['name'])
    rmdir(extract_dest)

    if root_name == None:
        remake_dir(extract_dest)
        archive.extractall(extract_dest)
    else:
        archive.extractall(dest_dir)
        shutil.move(os.path.join(dest_dir, root_name), extract_dest)
    
    archive.close()

def download_depend(dest_dir, temp_dir, depend):
    name = depend['name']
    url = depend['zipball_url']
    componment = urllib.parse.urlparse(url)
    download_filepath = os.path.join(temp_dir, '{}-{}.zip'.format(name, depend['version']))

    if not os.path.exists(download_filepath):
        http = urllib3.PoolManager()
        r = http.request('GET', url)
        if not r.status == 200:
            raise Exception('download {} from {} failed: {}'.format(name, url, r.status))
        
        fp = open(download_filepath, 'wb')
        fp.write(r.data)
        fp.close()

    extract_zipball(download_filepath, dest_dir, depend)

def install_depend(deps_root_dir, temp_dir, depend):
    name = depend['name']
    print('* install depend: ' + name)
    download_depend(deps_root_dir, temp_dir, depend)    

if __name__ == '__main__':
    cmd = parser.parse_args()
    deps_root_dir = os.path.abspath(cmd.deps_dir)
    if cmd.clear:
        remake_dir(deps_root_dir)
    
    temp_dir = os.path.join(deps_root_dir, 'download_temp')
    makedir_if_not_exists(temp_dir)
    print('* deps root dir: ' + deps_root_dir)
    print('* temp dir: ' + temp_dir)
    
    for depend in deps:
        install_depend(deps_root_dir, temp_dir, depend)
    print('* done!!!')